package strings

import "strconv"

func SubStr(str string, start int, length ...int) string {

	runeStr := []rune(str)
	lenStr := len(runeStr)

	if len(length) > 0 && length[0] == 0 {
		return ""
	}

	if start < 0 {
		start = lenStr + start
		if start < 0 {
			start = 0
		}
	}
	if start > lenStr {
		start = lenStr
	}

	end := lenStr
	if len(length) > 0 {
		if length[0] > 0 {
			end = start + length[0]
		} else if length[0] < 0 {
			end = lenStr + length[0]
		}
	}

	if end > lenStr {
		end = lenStr
	}

	if start > end {
		start, end = end, start
	}
	return string(runeStr[start:end])

}

type EscapeString string

func (this EscapeString) MarshalJSON() ([]byte, error) {
	return []byte(strconv.QuoteToASCII(string(this))), nil
}
